<template>
	<view class="face-recognition-container">
		<view class="header">
			<text class="title">人脸识别</text>
			<text class="close" @tap="goBack">×</text>
		</view>
		
		<view class="camera-container">
			<camera
				device-position="front"
				flash="off"
				@error="handleError"
				class="camera"
			></camera>
			<view class="face-frame"></view>
			<view class="scan-line"></view>
		</view>
		
		<view class="tips">
			<text class="tips-text">请将脸部置于框内</text>
			<text class="device-name">{{ deviceInfo.name }}</text>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				deviceInfo: null,
				isRecognizing: false,
				timer: null,
				cameraContext: null
			}
		},
		onLoad(options) {
			// 获取设备信息
			if (options.device) {
				this.deviceInfo = JSON.parse(decodeURIComponent(options.device));
			}
			// 创建相机上下文
			this.cameraContext = uni.createCameraContext();
			// 开始定时拍照
			this.startTimer();
		},
		onUnload() {
			// 页面卸载时停止定时器
			this.stopTimer();
		},
		methods: {
			goBack() {
				this.stopTimer();
				uni.navigateBack();
			},
			handleError(e) {
				console.error('相机错误：', e.detail);
				uni.showToast({
					title: '相机启动失败',
					icon: 'none'
				});
			},
			startTimer() {
				// 清除可能存在的旧定时器
				this.stopTimer();
				// 创建新的定时器，每2秒执行一次拍照
				this.timer = setInterval(() => {
					if (!this.isRecognizing) {
						this.takePhoto();
					}
				}, 2000);
			},
			stopTimer() {
				if (this.timer) {
					clearInterval(this.timer);
					this.timer = null;
				}
			},
			takePhoto() {
				if (this.isRecognizing) return;
				this.isRecognizing = true;
				
				this.cameraContext.takePhoto({
					quality: 'high',
					success: (res) => {
						console.log('拍照成功：', res);
						// 获取到图片临时路径
						const tempImagePath = res.tempImagePath;
						// 上传图片到服务器
						this.uploadImage(tempImagePath);
					},
					fail: (err) => {
						console.error('拍照失败：', err);
						this.isRecognizing = false;
						uni.showToast({
							title: '拍照失败，请重试',
							icon: 'none'
						});
					}
				});
			},
			uploadImage(tempImagePath) {
				uni.showLoading({ title: '识别中...' });
				console.log('图片路径：', tempImagePath);
				// 将图片转换为base64
				uni.getFileSystemManager().readFile({
					filePath: tempImagePath,
					encoding: 'base64',
					success: (res) => {
						// 发送图片到后端
						uni.request({
							url: 'http://localhost:9050/opencv/door/face',
							method: 'POST',
							header: {
								"token": uni.getStorageSync('token')
							},
							data: {
								image: res.data,
								deviceId: this.deviceInfo.deviceSn
							},
							success: (response) => {
								uni.hideLoading();
								if (response.data.code==200) {
									// 识别成功，停止定时器
									this.stopTimer();
									uni.showToast({
										title: '识别成功',
										icon: 'success',
										duration: 1500,
										success: () => {
											setTimeout(() => {
												uni.navigateBack();
												// 触发开门
												uni.$emit('unlock-success', this.deviceInfo);
											}, 1500);
										}
									});
								} else {
									uni.showToast({
										title: response.data.message || '识别失败',
										icon: 'none',
										duration: 1000
									});
									this.isRecognizing = false;
								}
							},
							fail: (err) => {
								uni.hideLoading();
								console.error('请求失败：', err);
								uni.showToast({
									title: '网络错误，请重试',
									icon: 'none',
									duration: 1000
								});
								this.isRecognizing = false;
							}
						});
					},
					fail: (err) => {
						uni.hideLoading();
						console.error('读取图片失败：', err);
						uni.showToast({
							title: '处理图片失败，请重试',
							icon: 'none',
							duration: 1000
						});
						this.isRecognizing = false;
					}
				});
			}
		}
	}
</script>

<style>
	.face-recognition-container {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: #000;
		z-index: 999;
	}
	
	.header {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 40rpx;
		z-index: 1000;
	}
	
	.title {
		color: #fff;
		font-size: 36rpx;
		font-weight: bold;
	}
	
	.close {
		color: #fff;
		font-size: 48rpx;
		padding: 0 20rpx;
	}
	
	.camera-container {
		position: relative;
		width: 100%;
		height: 100vh;
	}
	
	.camera {
		width: 100%;
		height: 100%;
	}
	
	.face-frame {
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		width: 500rpx;
		height: 500rpx;
		border: 4rpx solid #4A90E2;
		border-radius: 20rpx;
	}
	
	.scan-line {
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		width: 500rpx;
		height: 2rpx;
		background: #4A90E2;
		animation: scan 2s linear infinite;
	}
	
	@keyframes scan {
		0% {
			top: 30%;
		}
		50% {
			top: 70%;
		}
		100% {
			top: 30%;
		}
	}
	
	.tips {
		position: fixed;
		bottom: 100rpx;
		left: 0;
		right: 0;
		text-align: center;
	}
	
	.tips-text {
		display: block;
		color: #fff;
		font-size: 32rpx;
		margin-bottom: 20rpx;
	}
	
	.device-name {
		display: block;
		color: rgba(255, 255, 255, 0.8);
		font-size: 28rpx;
	}
</style> 